package com.utils.httphelper;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求其他工程servlet的工具类
 * 	
 * 调用Sunshine工程servlet 拒绝节点结束流程
 * Map<String, Object> resultMap = conSercletUtil.applyOtherProjectServlet(map, SERVLETURL);
 */
//@Component("pc.conServletUtil")
public class ConServletUtil {
	
	@SuppressWarnings("unchecked")
	public Map<String,Object> applyOtherProjectServlet(Map<String,Object> map,String urlStr){
		
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("isSucc", "false");
		resMap.put("errorMess", "");
		
		if(map==null||map.isEmpty()){
			return resMap;
		}
		
		//调用sunshineIntf中servlet
		HttpURLConnection conn = null;
		OutputStream out = null;
		ObjectOutputStream objectOut =null;
		InputStream is =null;
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
			conn.setRequestProperty("User-Agent", "top-sdk-java");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//			conn.setConnectTimeout(3000);
//			conn.setReadTimeout(60000);
			out = conn.getOutputStream();
			objectOut= new ObjectOutputStream(out);
			objectOut.writeObject(map);
			objectOut.flush();
			objectOut.close();
			
			//获取servlet返回值
			is = conn.getInputStream();
			ObjectInputStream n = new ObjectInputStream(is);
			resMap = (Map<String, Object>) n.readObject();
		}catch(Exception e){
			e.printStackTrace();
			System.out.println(e.getMessage());
		}finally {
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(objectOut!=null){
				try {
					objectOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(conn!=null){
				conn.disconnect();
			}
		}
		
		return resMap;
	}
}

